<template>
	<el-card>
		<div class="scheduleDetailBox" style="height: 100%" v-loading="boxLoading">
			<div class="scheduleDetailTopBox">
				<div style="height: 100%; width: 100%" id="scheduleDetailContainer"></div>
			</div>
			<!-- 上下侧边 -->
			<div title="上下侧边栏" class="flowBottomResize"></div>
			<div class="flowBottomBox">
				<el-tabs class="flowBottomTabs">
					<el-tab-pane>
						<template #label>
							<span class="flowCustomTabsLabel">
								<el-icon><Postcard /></el-icon>&nbsp;
								<span>日志信息</span>
							</span>
						</template>
						<ReadOnlyStudio id="flowConsoleLog" ref="flowConsoleLogRef" style="height: 100%"></ReadOnlyStudio>
					</el-tab-pane>
				</el-tabs>
			</div>
		</div>
	</el-card>

	<!-- 下载流程图 -->
	<div id="snapshotDownloadId" v-show="false"></div>

	<!-- 节点框 -->
	<el-drawer size="45%" v-model="nodeVisable" direction="rtl" :append-to-body="true">
		<template #header>
			<h4>{{ nodeDataForm.properties.name }}</h4>
		</template>
		<template #default>
			<el-descriptions title="" :column="1" size="large" border>
				<el-descriptions-item label="名称">{{ nodeDataForm.properties.name }}</el-descriptions-item>
				<el-descriptions-item label="作业类型">{{ nodeDataForm.properties.taskTypeVal }}</el-descriptions-item>
				<el-descriptions-item label="权重">{{ nodeDataForm.properties.weight }}</el-descriptions-item>
				<el-descriptions-item label="遇错是否继续">{{ nodeDataForm.properties.failGoOn ? '是' : '否' }}</el-descriptions-item>
				<el-descriptions-item label="备注">{{ nodeDataForm.properties.note }}</el-descriptions-item>
			</el-descriptions>
		</template>
	</el-drawer>

	<!-- 调度任务保存 -->
	<el-dialog v-model="configVisible" title="调度配置">
		<el-descriptions title="" :column="1" size="large" border>
			<el-descriptions-item label="调度名称">{{ scheduleForm.name }}</el-descriptions-item>
			<el-descriptions-item label="周期执行">{{ scheduleForm.ifCycle ? '是' : '否' }}</el-descriptions-item>
			<el-descriptions-item label="cron表达式" v-if="scheduleForm.ifCycle">{{ scheduleForm.cron }}</el-descriptions-item>
			<el-descriptions-item label="备注">{{ scheduleForm.note }}</el-descriptions-item>
		</el-descriptions>
	</el-dialog>
</template>

<script setup lang="ts" name="Data-developmentScheduleFlow">
import { reactive, ref, onMounted, nextTick, watch, onBeforeUnmount } from 'vue'
import LogicFlow from '@logicflow/core'
import { Menu, Control, SelectionSelect, DndPanel, Snapshot } from '@logicflow/extension'
import '@logicflow/core/dist/style/index.css'
import '@logicflow/extension/lib/style/index.css'
import TaskModel from '../schedule/UserTaskNode.js'
import FlowLink from '../schedule/FlowLink.js'
import reset from '../../../assets/hmm/10.png'
import { useScheduleApi, runFlowApiTwo, getConsoleLogApi, getNodeInfoApi } from '@/api/data-development/schedule'
import TaskHistory from '../task-history/index.vue'
import { ElMessage, ElNotification } from 'element-plus'
// import ReadOnlyStudio from '../../task-scheduling/production/readonly-studio.vue'
import ReadOnlyStudio from '../production/readonly-studio-two.vue'
import { estimatBoolean } from '@/api/auth-hm'
const props = defineProps(['childProp'])
const flowConsoleLogRef = ref()
//cron表达式，流程配置
const configVisible = ref(false)

const graphData = {
	nodes: [],
	edges: []
}
const state = reactive({
	timer: null,
	timerTwo: null
})
const scheduleForm = reactive({
	id: '',
	recordId: '',
	name: '',
	ifCycle: '',
	cron: '',
	note: '',
	nodes: [],
	edges: [],
	groupId: null,
	tableId: '',
	isShowtaskNode: false
})
watch(props, newValue => {
	scheduleForm.groupId = newValue.childProp
})
const boxLoading = ref(true)
const init = id => {
	scheduleForm.tableId = id
	useScheduleApi(id).then(res => {
		Object.assign(scheduleForm, res.data)
		graphData.nodes = scheduleForm.nodes
		graphData.edges = scheduleForm.edges
		//渲染
		lf.render(graphData)
		boxLoading.value = false
	})
}

//节点编辑框
const nodeVisable = ref(false)

const nodeDataForm = reactive({
	id: '',
	log: '',
	startTime: '',
	endTime: '',
	properties: {
		id: '',
		nodeRecordId: '',
		name: '',
		taskType: '',
		taskTypeVal: '',
		taskId: '',
		note: '',
		failGoOn: '',
		weight: 1,
		runStatus: ''
	},
	type: '',
	x: 490,
	y: 230
})

let lf = null
onMounted(() => {
	nextTick(() => {
		scheduleForm.isShowtaskNode = false
		//加载流程引擎
		lf = new LogicFlow({
			container: document.querySelector('#scheduleDetailContainer'),
			grid: {
				visible: true,
				type: 'mesh',
				size: 10,
				config: {
					color: '#eeeeee'
				}
			},
			//只看不编辑
			isSilentMode: true,
			// 注册组件
			plugins: [Menu, Control, SelectionSelect, DndPanel, Snapshot]
		})
		//注册任务节点
		lf.register(TaskModel)
		//注册连线
		lf.register(FlowLink)
		lf.setDefaultEdgeType('flow-link')
		document.getElementById('snapshotDownloadId').addEventListener('click', () => {
			lf.getSnapshot()
		})
		//左侧面板
		lf.extension.dndPanel.setPatternItems([
			{
				label: '配置信息',
				className: 'dnd-class',
				icon: '',
				callback: () => {
					configVisible.value = true
				}
			},
			{
				label: '导出',
				className: 'dnd-class',
				icon: '',
				callback: () => {
					document.getElementById('snapshotDownloadId').dispatchEvent(new MouseEvent('click'))
				}
			},
			{
				label: '恢复默认',
				className: 'dnd-class',
				icon: reset,
				callback: () => {
					initThree(scheduleForm.tableId)
				}
			}
		])

		lf.setTheme({
			/* rect: {
			    fill: '#fffae1',
			    stroke: '#000000',
			    strokeWidth: 2,
			  }, */
			snapline: {
				stroke: '#ace2ff', // 对齐线颜色
				strokeWidth: 1 // 对齐线宽度
			}
		})
		//设置右键菜单
		// lf.extension.menu.setMenuConfig({
		// 	nodeMenu: [
		// 		{
		// 			text: '查看',
		// 			callback(node) {
		// 				nodeEdit(node)
		// 			}
		// 		}
		// 	], // 覆盖默认的节点右键菜单
		// 	edgeMenu: false, // 删除默认的边右键菜单
		// 	graphMenu: [] // 覆盖默认的边右键菜单，与false表现一样
		// })
		//渲染
		//lf.render(graphData)
	})
})

const initThree = id => {
	useScheduleApi(id).then(res => {
		Object.assign(scheduleForm, res.data)
		graphData.nodes = scheduleForm.nodes
		graphData.edges = scheduleForm.edges
		//渲染
		lf.render(graphData)
		boxLoading.value = false
	})
	//加载流程引擎
	lf = new LogicFlow({
		container: document.querySelector('#scheduleDetailContainer'),
		grid: {
			visible: true,
			type: 'mesh',
			size: 10,
			config: {
				color: '#eeeeee'
			}
		},
		//只看不编辑
		isSilentMode: true,
		// 注册组件
		plugins: [Menu, Control, SelectionSelect, DndPanel, Snapshot]
	})
	//注册任务节点
	lf.register(TaskModel)
	//注册连线
	lf.register(FlowLink)
	lf.setDefaultEdgeType('flow-link')
	document.getElementById('snapshotDownloadId').addEventListener('click', () => {
		lf.getSnapshot()
	})
	//左侧面板
	lf.extension.dndPanel.setPatternItems([
		{
			label: '配置信息',
			className: 'dnd-class',
			icon: '',
			callback: () => {
				configVisible.value = true
			}
		},
		{
			label: '导出',
			className: 'dnd-class',
			icon: '',
			callback: () => {
				document.getElementById('snapshotDownloadId').dispatchEvent(new MouseEvent('click'))
			}
		},
		{
			label: '恢复默认',
			className: 'dnd-class',
			icon: reset,
			callback: () => {
				initThree(scheduleForm.tableId)
			}
		}
	])

	lf.setTheme({
		/* rect: {
			    fill: '#fffae1',
			    stroke: '#000000',
			    strokeWidth: 2,
			  }, */
		snapline: {
			stroke: '#ace2ff', // 对齐线颜色
			strokeWidth: 1 // 对齐线宽度
		}
	})
	//设置右键菜单
	lf.extension.menu.setMenuConfig({
		nodeMenu: [
			{
				text: '查看',
				callback(node) {
					nodeEdit(node)
				}
			}
		], // 覆盖默认的节点右键菜单
		edgeMenu: false, // 删除默认的边右键菜单
		graphMenu: [] // 覆盖默认的边右键菜单，与false表现一样
	})
}

/**
 * 运行流程
 */

const runFlow = async id => {
	clearInterval(state.timer)
	clearInterval(state.timerTwo)
	await estimatBoolean(id).then(async (res: any) => {
		if (res.code == 0) {
			if (res.data == '0') {
				const { data } = await runFlowApiTwo(id)
				ElNotification.closeAll()
				//获取日志
				getConsoleLog(data)
			} else {
				// 根据  获取  任务 id
				const { data } = await runFlowApiTwo(id)
				ElNotification.closeAll()
				// let data = '70810'
				//获取日志
				getConsoleLog(data)
				//设置节点状态
				setNodeStatus(data)
			}
		} else {
			ElMessage.error(res.msg)
		}
	})
	//获取recordId
	//提示
	// ElNotification({
	// 	title: '提示',
	// 	message: '正在执行流程，请耐心等待。。。',
	// 	duration: 0,
	// 	zIndex: 9999,
	// 	type: 'success'
	// })
}

//流程结束标识
const flowEnd = ref(false)
//每1s获取一次日志
const getConsoleLog = (recordId: any) => {
	getConsoleLogApi(recordId).then(res => {
		//设置log
		if (res.data.log != flowConsoleLogRef.value.getEditorValue()) {
			flowConsoleLogRef.value.setEditorValue(res.data.log)
		}
		//如果没结束，再次调用
		if (!res.data.end) {
			state.timer = setTimeout(() => {
				getConsoleLog(recordId)
			}, 1500)
		} else {
			flowEnd.value = true
		}
	})
}

//设置每个节点的状态，成功-绿色 失败-红色
const setNodeStatus = (recordId: any) => {
	if (!flowEnd.value) {
		setNodeInfo(recordId)
		//递归
		state.timerTwo = setTimeout(() => {
			setNodeStatus(recordId)
		}, 1500)
	} else {
		setNodeInfo(recordId)
		// ElMessage.success('调度流程执行完毕，请前往调度记录查看具体执行情况！')
		ElNotification.closeAll()
	}
}

const setNodeInfo = (recordId: any) => {
	getNodeInfoApi(recordId).then(res => {
		let nodeList = res.data
		for (let i in nodeList) {
			const nodeInfo = nodeList[i]
			const nodeModel = lf.getNodeModelById(nodeInfo.scheduleNodeNo)
			if (nodeModel) {
				const properties = nodeModel.getProperties()
				if (nodeInfo.runStatus == 3) {
					properties.style = { border: '3px solid #06c733' }
					//关闭动画
					if (nodeInfo.edgeId) {
						lf.closeEdgeAnimation(nodeInfo.edgeId)
					}
				} else if (nodeInfo.runStatus == 4) {
					properties.style = { border: '3px solid #e30000' }
					//关闭动画
					if (nodeInfo.edgeId) {
						lf.closeEdgeAnimation(nodeInfo.edgeId)
					}
				} else {
					//开启边的动画效果
					if (nodeInfo.edgeId) {
						lf.openEdgeAnimation(nodeInfo.edgeId)
					}
				}
				nodeModel.setProperties(properties)
			}
		}
	})
}
onBeforeUnmount(() => {
	clearFun()
})
const clearFun = () => {
	clearInterval(state.timer)
	clearInterval(state.timerTwo)
}

/**
 * 编辑节点
 */
const nodeEdit = (data: any) => {
	nodeVisable.value = true
	Object.assign(nodeDataForm, data)
}

const disposeFun = () => {
	// editor.dispose()
	flowConsoleLogRef.value.disposeFun()
}

defineExpose({
	init,
	runFlow,
	disposeFun
})
</script>

<style lang="scss" scoped>
#scheduleDetailContainer {
	height: 100%;
	width: 100%;
	/* height: calc(100vh - 200px); */
}
.dnd-class {
	padding: 7px;
}
/* 主矿体 */
.scheduleDetailTopBox {
	height: 70%;
	&.on {
		::v-deep(.task-node) {
			border-color: pink !important;
		}
	}
}
.flowBottomResize {
	overflow: hidden;
	cursor: s-resize;
	width: 100%;
	height: 10px;
	background-color: #d6d6d6;
	margin: 0 auto;
	border-radius: 5px;
	text-align: center;
	line-height: 3px;
	font-size: 32px;
	color: white;
}
.flowBottomBox {
	height: calc(30% - 10px);
}
/* .flowBottomTabs .el-tabs__content {
	height: calc(100% - 40px);
	padding: 0;
} */
/* 每个tab高度设置为100% */
// #el-tabs__content {
// 	height: 100%;
// }
// #flowConsoleLog {
// 	height: 500px;
// }
// #el-tabs__content ::v-deep(.el-tabs__content) {
// 	height: 100% !important;
// }
/* #el-tabs__content  .el-tabs__content  .el-tab-pane {
	height: 100%;
} */
.flowBottomBox .flowBottomTabs {
	height: 100%;
	::v-deep(.el-tabs__content) {
		height: calc(100% - 40px);
		.el-tab-pane {
			height: 100%;
		}
	}
}
// .flowBottomBox .el-tabs__content {
// 	height: calc(100% - 55px);
// }
</style>